package com.orientation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orientation.commom.exception.CustomException;
import com.orientation.entity.Bed;
import com.orientation.entity.Building;
import com.orientation.entity.Room;
import com.orientation.mapper.BedMapper;
import com.orientation.mapper.BuildingMapper;
import com.orientation.mapper.RoomMapper;
import com.orientation.service.BedService;
import com.orientation.service.BuildingService;
import com.orientation.service.RoomService;
import com.orientation.utils.BeanConvertUtils;
import com.orientation.utils.PageUtils;
import com.orientation.vo.RoomBedVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.Collator;
import java.util.*;

/**
 * <p>
 * 报到 服务实现类
 * </p>
 *
 * @author xuandian
 * @since 2022-3-9
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements RoomService {
    @Resource
    private RoomMapper roomMapper;
    @Resource
    private BuildingMapper buildingMapper;
    @Resource
    private BuildingService buildingService;
    @Resource
    private RoomService roomService;
    @Resource
    private BedService bedService;
    @Resource
    private BedMapper bedMapper;
    @Resource
    private FilesService filesService;

    @Override
    @Transactional
    public void insertRoom(Room room) {
        if (!StringUtils.hasLength(room.getName())) {
            throw new CustomException("18", "房间号必填");
        }
        if (!StringUtils.hasLength(room.getBuildingId()) && !StringUtils.hasLength(room.getFloor())) {
            throw new CustomException("18", "所属楼栋和楼层信息必填");
        } else {
            if (StringUtils.hasLength(room.getName()) && room.getName().length() > 3) {
                throw new CustomException("18", "房间号最大只能为三位");
            }
            if (!room.getFloor().equals(room.getName().substring(0, 1))) {
                throw new CustomException("18", "房间号填写错误");
            }
            Building building = buildingService.getOne(Wrappers.<Building>lambdaQuery().eq(StringUtils.hasLength(room.getBuildingId()), Building::getSid, room.getBuildingId()).eq(StringUtils.hasLength(room.getFloor()), Building::getFloor, room.getFloor()));
            if (building == null) {
                throw new CustomException("18", "所属楼栋和楼层信息填写错误");
            } else {
                Room one = roomMapper.selectOne(new LambdaQueryWrapper<Room>().eq(Room::getName, room.getName()).eq(Room::getBuildingId, room.getBuildingId()).eq(Room::getFloor, room.getFloor()));
                if (one != null) {
                    throw new CustomException("18", "此房间已经存在");
                } else {
                    building.setRoom(building.getRoom() == 0 ? 1 : building.getRoom() + 1);
                    save(room);
                    buildingService.updateById(building);
                }
            }
        }
    }

    @Override
    public Page<RoomBedVo> queryRoomBedVo(Integer pageNum, Integer pageSize, String buildingId, String roomName) {
        List<RoomBedVo> roomBedVos = new ArrayList<>();
//        if (StringUtils.hasLength(roomName)) {
        List<Room> rooms = roomService.list(Wrappers.<Room>lambdaQuery().eq(StringUtils.hasLength(buildingId), Room::getBuildingId, buildingId).eq(StringUtils.hasLength(roomName), Room::getName, roomName));
        roomBedVos = BeanConvertUtils.copyListProperties(rooms, RoomBedVo::new);
        if (!CollectionUtils.isEmpty(roomBedVos)) {
            for (RoomBedVo roomBedVo : roomBedVos) {
                List<Bed> beds = bedMapper.selectList(new LambdaQueryWrapper<Bed>().eq(StringUtils.hasLength(roomBedVo.getSid()), Bed::getRoomId, roomBedVo.getSid()));
                if (!CollectionUtils.isEmpty(beds)) {
                    long onlineNum = beds.stream().filter(bed -> !StringUtils.hasLength(bed.getStudentId())).count();
                    if (onlineNum == 0) {
                        roomBedVo.setColorString("已住满");
                    } else {
                        roomBedVo.setColorString("未住满");
                    }
                } else {
                    roomBedVo.setColorString("待维护");
                }
                roomBedVo.setBedList(comparatorChina(beds));
            }
        }
//        }
//        else {
//            List<Bed> beds = bedMapper.selectList(new LambdaQueryWrapper<Bed>().eq(StringUtils.hasLength(roomName), Bed::getName, roomName));
//            if (!CollectionUtils.isEmpty(beds)) {
//                Map<String, List<Bed>> listMap = beds.stream().collect(groupingBy(Bed::getRoomId));
//                List<String> buildIds = beds.stream().distinct().map(Bed::getRoomId).collect(Collectors.toList());
//                List<Room> rooms = roomService.list(Wrappers.<Room>lambdaQuery().in(!CollectionUtils.isEmpty(buildIds), Room::getBuildingId, buildIds).eq(StringUtils.hasLength(buildingId), Room::getBuildingId, buildingId));
//                roomBedVos = BeanConvertUtils.copyListProperties(rooms, RoomBedVo::new);
//                if (!CollectionUtils.isEmpty(roomBedVos)) {
//                    List<RoomBedVo> finalRoomBedVos = roomBedVos;
//                    listMap.forEach((roomId, value) -> {
//                        for (RoomBedVo roomBedVo : finalRoomBedVos) {
//                            if (roomBedVo.getSid().equals(roomId)) {
//                                roomBedVo.setBedList(value);
//                            }
//                        }
//                    });
//                }
//            }
//        }
        return PageUtils.getPage(roomBedVos, pageNum, pageSize);
    }

    @Override
    public void updateRoomStatus(MultipartFile[] files, String sid) {
        if (!StringUtils.hasLength(sid)) {
            throw new CustomException("18", "房间id必须填写");
        }
        Room room = this.getById(sid);
        //文件上传
        if (files != null && files.length > 0) {
            List<String> stringUrls = filesService.getStringUrls(files);
            if (!CollectionUtils.isEmpty(stringUrls)) {
                room.setRoomurl(stringUrls == null ? null : org.apache.commons.lang3.StringUtils.join(stringUrls, ","));
            }
        }
        this.updateById(room);

    }

    /**
     * 按中文首字母排序
     *
     * @param result
     * @return result
     */
    private List<Bed> comparatorChina(List<Bed> result) {
        Comparator comparator = Collator.getInstance(Locale.CHINA);
        Collections.sort(result, (o1, o2) -> comparator.compare(o1.getName(), o2.getName()));
        return result;
    }

}
